<template>
  <div class="cart-item">
    <van-checkbox
      :value="checked"
      :name="'cartItem_' + cartObj.id"
      @change="onCheckBoxChange"
      @click="onCheckBoxClick"
    >
      <van-swipe-cell>
        <van-card
          :num="cartObj.count"
          :price="getPrice"
          :desc="cartObj.desc"
          :title="cartObj.name"
          :thumb="cartObj.thumbnail"
          class="goods-card"
        />
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="onDeleteBtnClick"
          />
        </template>
      </van-swipe-cell>
    </van-checkbox>
  </div>
</template>

<script>
export default {
  name: 'cartItem',
  props: {
    cart: {
      type: Object,
      required: true
    },
    // 是否选中
    isChecked: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      cartObj: this.cart,
      // 当前购物车条目是否被选中
      checked: this.isChecked
    }
  },
  methods: {
    // 点击 删除 按钮
    onDeleteBtnClick() {
      console.log('点击删除')
      this.$emit('delete', { id: this.cartObj.id })
    },
    // 组件被点击
    onCheckBoxClick(e) {
      console.log('购物车组件被点击')
      this.checked = !this.checked
    },
    // 复选框 change 事件
    onCheckBoxChange(checked) {
      this.$emit('choose', {
        id: this.cartObj.id,
        type: checked,
        price: this.getPrice * 100
      })
    }
  },
  computed: {
    // 计算当前购物车条目的价格
    getPrice() {
      return ((this.cartObj.price * this.cartObj.count) / 100).toFixed(2)
    }
  }
}
</script>

<style>
.cart-item {
  box-sizing: border-box;
  padding-left: 5px;
}
.goods-card {
  margin: 0;
  background-color: #fff;
  width: 100%;
}
.van-card {
  width: 95vw;
}
.van-card__price-currency,
.van-card__price-integer,
.van-card__price-decimal {
  color: #8b0000;
}
.van-card__num {
  margin: 0 5px 0 3px;
}
</style>
